local UI = SecretaryUI

UI.DRAG_HANDLE_HALF_WIDTH = 2

local function GetTableObject(this)
	return this:GetParent():GetParent().object
end

local function HeaderDrag_OnMouseDown(this)
	GetTableObject(this):OnHeaderDragStart(this:GetParent().col)
	this.dragging = true
end

local function HeaderDrag_OnMouseUp(this)
	if not this.dragging then return end
	GetTableObject(this):OnHeaderDragStop()
	this.dragging = nil
end

local function HeaderDrag_Layout(this)
	local object = GetTableObject(this)
	local col = this:GetParent().col
	local offset = object:GetColumnOffset(col) + object:GetColumnWidth(col)

	this:ClearAllPoints()
	this:SetPoint("TOPLEFT", object.frame, "TOPLEFT", offset - UI.DRAG_HANDLE_HALF_WIDTH, 0)
	this:SetPoint("BOTTOMRIGHT", object.frame, "BOTTOMLEFT", offset + UI.DRAG_HANDLE_HALF_WIDTH, 0)
end

local function HeaderDrag_OnEnter(this)
	SetCursor("ATTACK_CURSOR")
end

local function HeaderDrag_OnLeave(this)
	SetCursor(nil)
end

local function MakeHeaderDrag (parent)
	local drag = CreateFrame("Frame", parent:GetName().."Drag", parent)
	drag:EnableMouse(true)
	drag:SetMovable(true)
	drag:SetScript("OnMouseDown", HeaderDrag_OnMouseDown)
	drag:SetScript("OnMouseUp", HeaderDrag_OnMouseUp)
	drag:SetScript("OnEnter", HeaderDrag_OnEnter)
	drag:SetScript("OnLeave", HeaderDrag_OnLeave)
	drag.Layout = HeaderDrag_Layout
	return drag
end

UI.MakeHeaderDrag = MakeHeaderDrag
